import Authorization.User;
import Commands.CommandHandler;
import IO.Output;
import Levels.Complexity;
import Questions.QuestionsBook;
import Session.TestSession;
import Source.MsgKeys;
import Source.NotificationsStorage;
import xmls.SaxParserQuestions;

import java.io.IOException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Authorization.User: Инесса
 * Date: 23.10.13
 * Time: 1:26
 * To change this template use File | Settings | File Templates.
 */
public class Controller {
    NotificationsStorage notification;
    QuestionsBook questionsBook;
    private int sessionResult = 0;

    public Controller(){
        notification = new NotificationsStorage();
        questionsBook = new SaxParserQuestions().getQuestionsBook();
        TestSession.getInstance().setQuestionsBook(questionsBook);
       }

    public void performActions(User user) throws IOException {

        Output.printLineMsg(notification.getNotification(MsgKeys.HELLO_MSG) + user.getLogin());
        if (!user.getLogin().equals("admin")) {
            notification.notify(MsgKeys.START_TEST_MSG);
            testingUser();
        } else {
            System.out.println("Hello admin:)");
        }
    }

    private void testingUser() {
        Scanner scanner = new Scanner(System.in);
        String userInput;
        CommandHandler handler = new CommandHandler();
        TestSession.getInstance().askQuestion();
        while (!TestSession.getInstance().isEndSession()){
             userInput = scanner.nextLine();
             TestSession.getInstance().setEnteredLine(userInput);
             handler.runCommand(userInput,TestSession.getInstance());
             switchChapter();
        }


    }

    private void switchChapter() {
        if(TestSession.getInstance().isLevelAnswered()){
            int levelResult=TestSession.getInstance().countAnsweredLevel();
            int LEVEL_MIN_RESULT = 3;
            if(levelResult>= LEVEL_MIN_RESULT){
                 passLevel();
                 sessionResult+=levelResult;
             } else {
               TestSession.getInstance().refreshChapterLevel();
            }

        }
    }

    private void passLevel() {
        if(isLastLevel()){
            TestSession.getInstance().endSession();
            Output.printLineMsg("CONGRATULATIONS"+sessionResult);
        }
        else {
            if(!isMediumComplexity()){
                TestSession.getInstance().upChapterComplexity();
            } else {
               TestSession.getInstance().nextChapter();
            }
        }
    }

    private boolean isMediumComplexity(){
        return TestSession.getInstance().getChapterComplexity()==Complexity.MEDIUM;
    }

    private boolean isLastChapter(){
        return TestSession.getInstance().isLastChapter();
    }

    private boolean isLastLevel(){
        return isMediumComplexity()&&isLastChapter();
    }

}